import request from '../request'
import cache, {
  removeCache
} from '../cache'
import getOpenID from '../getOpenID'
 
// /api/good/
export const getGood = cache('goodList', async () => {
  const res = await request('/good/')
  return res
})

//  创建user good数据
export const addUserGood = async (goodId) => {
  const {
    openid
  } = await getOpenID()
  const goodList = await getGood()
  const goodItem = goodList.find(item => item.id === goodId)
  // console.log('goodItem' , goodItem);
  await request('/user-good/', {
    openid,
    user: openid,
    type: 'unharve',
    good: goodId,
    num: goodItem.min_num,
    harve_time: Date.now() + goodItem.harve_interval,
    out_time: Date.now() + goodItem.out_interval
  }, 'POST')
  removeCache('userGoodList')
}

// 获取用户的商品列表
export const getUserGood =cache('userGoodLIst', async () => {
  const {
    openid
  } = await getOpenID()
  const res = await request('/user-good/', {
    openid,
    type: 'unharve'
  })
//  把用户的商品列表按照 商品的id分组，形成一个对象的形式
  // [{good: 2, name:}, {good:3: name}]  => { 2: [{good: 2, name:}], 3: [{good:3: name}] }
  return res.reduce((prev, item) => {
    if (prev.hasOwnProperty(item.good)) {
      prev[item.good].unshift(item)
    } else {
      prev[item.good] = [item]
    }
    return prev
  }, {})
})

export const editUserGood = async (good) => {
  const {openid} = await getOpenID()
  await request(`/user-good/${good.id}/`, {
    openid, ...good
  }, 'PUT')
  removeCache('userGoodList')
}

